package com.lalameow.common.gui.bukkit;

import com.google.common.collect.Lists;
import com.lalameow.common.MeowCommon;
import com.lalameow.common.gui.PositionSlot;
import com.sun.istack.internal.Nullable;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;

import java.util.List;

/**
 * @author SettingDust.
 * Date 2018/6/1.
 */
public class BukkitGuiChest {
    private int row;
    private String title;
    private List<BukkitItemChest> items;

    public BukkitGuiChest(int row, String title) {
        this.row = row;
        this.title = title;
        this.items = Lists.newArrayList();
        Bukkit.getServer().getPluginManager().registerEvents(new GuiChestListener(),
                MeowCommon.getInstance());
    }

    /**
     * Overwrite the item in the slot.
     *
     * @param item the item to set.
     */
    public void setItem(BukkitItemChest item) {
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).getPositionSlot().equals(item.getPositionSlot())) {
                items.remove(i);
            }
        }
        items.add(item);
    }

    public void removeItem(PositionSlot slot) {
        for (int i = 0; i < items.size(); i++) {
            if (slot.equals(items.get(i).getPositionSlot())) {
                items.remove(i);
            }
        }
    }

    /**
     * @param slot the slot want to get.
     * @return is null when not find.
     */
    @Nullable
    public BukkitItemChest getItem(PositionSlot slot) {
        for (BukkitItemChest item : items) {
            if (item.getPositionSlot().equals(slot)) return item;
        }
        return null;
    }

    /**
     * Display a Chest gui to player.
     *
     * @param player the player to display this gui.
     */
    public void showGui(Player player) {
        Inventory inventory = Bukkit.createInventory(player, row * 9, title);
        for (BukkitItemChest item : items) {
            inventory.setItem(item.getPositionSlot().toIndex(), item.getItem().getItemStack());
        }
        player.openInventory(inventory);
    }

    class GuiChestListener implements Listener {
        @EventHandler
        public void onMove(InventoryClickEvent event) {
            if (event.getInventory().getTitle().equals(title)) {
                BukkitItemChest itemChest = getItem(new PositionSlot(event.getRawSlot()));
                if (!itemChest.isCanMove()) {
                    event.setCancelled(true);
                }
            }
        }
    }
}
